package com.uhu.web.handler.exception;

import com.uhu.common.ResponseData;
import com.uhu.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author liujunjie
 * @description 全局异常处理器
 * @create 2023-11-15 10:20
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public ResponseData exceptionHandler(Exception e) {
        log.error("GlobalExceptionHandler exceptionHandler error message: {}", e.getMessage(), e);
        return ResponseData.error("服务器内部错误，请联系管理员");
    }

    /**
     * validator校验异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseData methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        String errMessage = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        log.error("GlobalExceptionHandler methodArgumentNotValidException error message: {}", errMessage, e);
        return ResponseData.error(errMessage);
    }

    /**
     * 自定义异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    public ResponseData businessExceptionHandler(BusinessException e) {
        log.error("GlobalExceptionHandler businessExceptionHandler error message: {}", e.getMessage(), e);
        return ResponseData.error(e.getMessage());
    }
}
